
var md5Utf_8 = require('./md5Utf_8.js');
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  md5Param: md5Param, 
}


//产生随机数函数
function RndNum() {
  return Math.floor(1000 + Math.random() * (1999 - 1000));
}

//字典升序排列方法  返回排序好的字符串
function ascending(dic) {

  var sdic = Object.keys(dic).sort();
  var key = "";
  var value = "";

  for (var ki in sdic) {

    value += dic[sdic[ki]];
  }
  //在次添加后缀的 秘钥参数
  var str = value + "captableWX";
  return str
}

//https://api.captable.cn/wx/user/get-user-info
function md5Param(data) {

  var nonces = RndNum();

  var params = {
    api_key: "2001",
    nonce: nonces,
    timestamp: (new Date()).valueOf(),
    version: "1.0",
    // sign_method: "md5",
  }
  //拼接传来的参数
  if(data){
    for (var key in data) {
      params[key] = data[key]
    }
  }
  
  // console.log(params)
  //得到拼接字符串
  var ascendingStr = ascending(params);
  // ascendingStr = ascendingStr.replace("\t","");
  // console.log("拼接字符串：" + ascendingStr)
  //加密

  var signStr = md5Utf_8.md5(ascendingStr);
  params.sign = signStr;
  
  return params;
  // console.log(params);
  // wx.request({
  //   url: url,
  //   data: params,
  //   method: method,
  //   header: {
  //     'content-type': 'application/x-www-form-urlencoded'
  //   },
  //   dataType: 'json',
  //   success: function (response) {
  //     return response;
  //   }
  // })
}